package com.ds.infra.rpc.core.loadbalance;

import com.ds.infra.rpc.registry.model.ServiceInstance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 作用：随机负载均衡策略
 *
 * @author WeiShaoying
 */
@Component("randomLoadBalance")
@Slf4j
public class RandomLoadBalance implements LoadBalance {

    @Override
    public Map<String, Object> select(List<Map<String, Object>> instances) {
        if (instances.isEmpty()) {
            log.error("No available instances");
            throw new RuntimeException("No service instance available");
        }
        int index = ThreadLocalRandom.current().nextInt(instances.size());
        Map<String, Object> selected = instances.get(index);
        log.debug("Random selected instance: {}", selected.get("serviceAddress"));
        return selected;
    }

    @Override
    public ServiceInstance selectInstance(List<ServiceInstance> instances) {
        return null;
    }
}
